package com.guigu.qingcheng.systemservice.controller;

import com.guigu.qingcheng.pojo.system.TbAdmin;
import com.guigu.qingcheng.pojo.system.TbLoginLog;
import com.guigu.qingcheng.systemservice.config.BCrypt;
import com.guigu.qingcheng.systemservice.config.WebUtil;
import com.guigu.qingcheng.systemservice.service.TbAdminService;
import com.guigu.qingcheng.systemservice.service.TbLoginLogService;
import com.guigu.qingcheng.utils.R;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/systemservice/login")
public class LoginController {

    @Autowired
    private TbAdminService service;

    @Autowired
    private TbLoginLogService logService;

    @Autowired
    private HttpServletRequest request;

    @PostMapping("/login")
    public R login(@RequestBody Map<String, Object> loginMap){
        List<TbAdmin> list = service.findList(loginMap);
        if(list.size() > 0){
            for(TbAdmin a: list){
              Boolean f = BCrypt.checkpw(loginMap.get("password").toString(), a.getPassword());
              if(f){
                  // 新增一条登录日志信息
                  TbLoginLog loginLog = new TbLoginLog();
                  loginLog.setLoginName(a.getLoginName());
                  String ip = request.getRemoteAddr();
                  loginLog.setIp(ip);//登录的IP地址
                  UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
                  Browser browser = userAgent.getBrowser();
                  loginLog.setBrowserName(browser.getName());//设置浏览器名称
                  loginLog.setLocation(WebUtil.getCityByIP(ip));//设置地区
                  loginLog.setLoginTime(new Date());//登录时间
                  logService.save(loginLog);
                  request.getSession().setAttribute("user", a);
                  return R.ok().data("user", list.get(0));
              }
            }
        }
        return R.error();
    }

    /**
     * 获取当前登录人
     * @param
     * @return
     */
    @GetMapping("/getUser")
    public R getUser(){
        TbAdmin user = (TbAdmin) request.getSession().getAttribute("user");
        System.out.println(user);
        return R.ok().data("user", user);
    }

    @GetMapping("/loginOut")
    public R loginOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.ok();
    }

}
